package com.example.hospitalsystemclient.ui.dashboard;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.hospitalsystemclient.Dataclass.Doctor;
import com.example.hospitalsystemclient.Dataclass.UrlData;
import com.example.hospitalsystemclient.R;

import com.example.hospitalsystemclient.databinding.FragmentDashboardBinding;
import com.example.hospitalsystemclient.ui.doctorDetail.DoctorDetailFragment;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class DashboardFragment extends Fragment implements DoctorAdapter.OnItemClickListener {

    private FragmentDashboardBinding binding;

    private List<Doctor> doctorList = new ArrayList<>();

    private UrlData urlData = new UrlData();

    private DoctorAdapter doctorAdapter;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        DashboardViewModel dashboardViewModel =
                new ViewModelProvider(this).get(DashboardViewModel.class);

        binding = FragmentDashboardBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        //下拉选择科室
        Spinner spinner = binding.officeSpinner;
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(),
                R.array.office_item, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // 获取选中的项
                String selectedItem = parent.getItemAtPosition(position).toString();

                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("officeName", selectedItem);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                // 创建一个请求体
                RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());

                // 创建一个 POST 请求
                Request request = new Request.Builder()
                        .url(urlData.getDoctorList())
                        .post(requestBody)
                        .build();

                OkHttpClient client = new OkHttpClient();

                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "网络问题", Toast.LENGTH_SHORT).show());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (response.isSuccessful()) {
                            final String responseData = response.body().string();
                            try{
                                JSONObject jsonObject = new JSONObject(responseData);
                                if(jsonObject.getBoolean("stat")){
                                    JSONArray dataArray = jsonObject.getJSONArray("datas");

                                    doctorList.clear();

                                    // 遍历 JSON 数组并填充数据
                                    for (int i = 0; i < dataArray.length(); i++) {
                                        JSONObject doctorObject = dataArray.getJSONObject(i);
                                        Doctor doctor = new Doctor();
                                        doctor.setDocId(doctorObject.getInt("doc_id"));
                                        doctor.setDocName(doctorObject.getString("doc_name"));
                                        doctor.setDocGender(doctorObject.getString("doc_gender"));
                                        doctor.setDocAge(doctorObject.getInt("doc_age"));
                                        doctor.setDocLevel(doctorObject.getString("doc_level"));
                                        doctor.setOfficeName(doctorObject.getString("office_name"));
                                        doctor.setImgAddr(doctorObject.getString("img_addr"));
                                        doctor.setDocPrice(doctorObject.getInt("doc_price"));

                                        // 添加到列表
                                        doctorList.add(doctor);
                                    }
                                    if(isAdded()){
                                        requireActivity().runOnUiThread(() -> {
                                            // 更新 UI
                                            doctorAdapter.updateData(doctorList);
                                        });
                                    }
                                } else {
                                    requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "失败" + response.code(), Toast.LENGTH_SHORT).show());
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "失败" + response.code(), Toast.LENGTH_SHORT).show());
                        }
                    }
                });
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // 当没有选项被选中时调用
            }
        });

        RecyclerView recyclerView = binding.recyclerView;
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        doctorAdapter = new DoctorAdapter(doctorList, this);
        recyclerView.setAdapter(doctorAdapter);

        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    @Override
    public void onItemClick(Doctor doctor) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("docId", doctor.getDocId());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
        Request request = new Request.Builder()
                .url(urlData.getDoctorDetail())
                .post(requestBody)
                .build();

        OkHttpClient client = new OkHttpClient();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "网络问题", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    final String responseData = response.body().string();
                    try {
                        JSONObject jsonObject = new JSONObject(responseData);
                        if (jsonObject.getBoolean("stat")) {
                            JSONObject doctorDetail = jsonObject.getJSONObject("datas");

                            DoctorDetailFragment doctorDetailFragment = new DoctorDetailFragment();

                            SharedPreferences sharedPreferences = requireActivity().getSharedPreferences("DoctorPrefs", 0);
                            SharedPreferences.Editor editor = sharedPreferences.edit();

                            editor.putLong("doc_id", doctorDetail.getLong("doc_id"));
                            editor.putString("doc_name", doctorDetail.getString("doc_name"));
                            editor.putString("office_name", doctorDetail.getString("office_name"));
                            editor.putString("doc_gender", doctorDetail.getString("doc_gender"));
                            editor.putInt("doc_age", doctorDetail.getInt("doc_age"));
                            editor.putString("doc_level", doctorDetail.getString("doc_level"));
                            editor.putInt("doc_price", doctorDetail.getInt("doc_price"));
                            editor.putString("doc_phone", doctorDetail.getString("doc_phone"));
                            editor.putString("img_addr", doctorDetail.getString("img_addr"));

                            editor.apply();

                            requireActivity().runOnUiThread(() -> {
                                // 跳转到医生详细信息 Fragment
                                NavController navController = Navigation.findNavController(requireActivity(), R.id.nav_host_fragment_activity_main);
                                navController.navigate(R.id.doctorDetailFragment);
                            });
                        } else {
                            requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "获取医生详细信息失败", Toast.LENGTH_SHORT).show());
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "获取医生详细信息失败", Toast.LENGTH_SHORT).show());
                }
            }
        });
    }

}